// 平台检测和数据同步工具

/**
 * 获取当前平台信息
 */
export const getPlatformInfo = () => {
  const info = {
    platform: 'unknown',
    isH5: false,
    isMiniProgram: false,
    isApp: false
  }

  // #ifdef H5
  info.platform = 'h5'
  info.isH5 = true
  // #endif

  // #ifdef MP-WEIXIN
  info.platform = 'mp-weixin'
  info.isMiniProgram = true
  // #endif

  // #ifdef APP-PLUS
  info.platform = 'app'
  info.isApp = true
  // #endif

  return info
}

/**
 * 检测跨平台数据不一致问题
 */
export const detectPlatformDataInconsistency = (chatStore) => {
  if (!chatStore) return null

  const platformInfo = getPlatformInfo()
  const stats = {
    platform: platformInfo.platform,
    totalChats: chatStore.chatHistory.length,
    emptyChats: chatStore.chatHistory.filter(chat => 
      !chat.messages || chat.messages.length === 0
    ).length,
    validChats: chatStore.chatHistory.filter(chat => 
      chat.messages && chat.messages.length > 0
    ).length,
    lastSyncTime: chatStore.lastSyncTime,
    hasCurrentChat: !!chatStore.currentChat
  }

  // 检测潜在问题
  const issues = []
  
  if (stats.emptyChats > 0) {
    issues.push({
      type: 'empty_chats',
      severity: 'warning',
      message: `发现 ${stats.emptyChats} 个空对话`,
      suggestion: '建议清理空对话'
    })
  }

  if (!stats.lastSyncTime) {
    issues.push({
      type: 'never_synced',
      severity: 'info',
      message: '从未同步过服务器数据',
      suggestion: '建议同步服务器数据'
    })
  } else {
    const lastSync = new Date(stats.lastSyncTime)
    const now = new Date()
    const diffHours = (now - lastSync) / (1000 * 60 * 60)
    
    if (diffHours > 24) {
      issues.push({
        type: 'sync_outdated',
        severity: 'warning',
        message: `距离上次同步已超过 ${Math.floor(diffHours)} 小时`,
        suggestion: '建议重新同步数据'
      })
    }
  }

  return {
    stats,
    issues,
    needsSync: issues.some(issue => 
      issue.type === 'never_synced' || issue.type === 'sync_outdated'
    ),
    needsCleanup: issues.some(issue => issue.type === 'empty_chats')
  }
}

/**
 * 生成平台数据报告
 */
export const generatePlatformReport = (chatStore) => {
  const detection = detectPlatformDataInconsistency(chatStore)
  
  if (!detection) {
    return '无法生成报告：聊天store未初始化'
  }

  const { stats, issues } = detection
  
  let report = `=== ${stats.platform.toUpperCase()} 平台数据报告 ===\n`
  report += `总对话数: ${stats.totalChats}\n`
  report += `有效对话: ${stats.validChats}\n`
  report += `空对话: ${stats.emptyChats}\n`
  report += `最后同步: ${stats.lastSyncTime ? new Date(stats.lastSyncTime).toLocaleString() : '从未同步'}\n`
  report += `当前对话: ${stats.hasCurrentChat ? '是' : '否'}\n\n`

  if (issues.length > 0) {
    report += '检测到的问题:\n'
    issues.forEach((issue, index) => {
      const severityIcon = issue.severity === 'warning' ? '⚠️' : 'ℹ️'
      report += `${index + 1}. ${severityIcon} ${issue.message}\n`
      report += `   建议: ${issue.suggestion}\n`
    })
  } else {
    report += '✅ 未发现问题\n'
  }

  return report
}

/**
 * 跨平台数据同步建议
 */
export const getCrossPlatformSyncAdvice = () => {
  const platformInfo = getPlatformInfo()
  
  const advice = {
    platform: platformInfo.platform,
    recommendations: []
  }

  if (platformInfo.isH5) {
    advice.recommendations.push({
      title: 'H5平台建议',
      actions: [
        '定期使用 window.forceSync() 强制同步',
        '使用 window.cleanupEmpty() 清理空对话',
        '检查浏览器是否清理了localStorage'
      ]
    })
  }

  if (platformInfo.isMiniProgram) {
    advice.recommendations.push({
      title: '小程序平台建议',
      actions: [
        '小程序数据存储相对稳定',
        '注意小程序版本更新可能清空数据',
        '可以手动触发同步确保数据一致性'
      ]
    })
  }

  advice.recommendations.push({
    title: '通用建议',
    actions: [
      '重要对话建议导出备份',
      '不同平台间通过账号服务器同步',
      '定期清理无用的空对话'
    ]
  })

  return advice
}

/**
 * 注册平台检测命令（开发用）
 */
export const registerPlatformCommands = (chatStore) => {
  if (typeof window !== 'undefined' && window.console) {
    console.log('=== 平台检测工具 ===')
    console.log('- window.platformReport() // 生成平台数据报告')
    console.log('- window.syncAdvice() // 获取同步建议')
    console.log('- window.detectIssues() // 检测数据问题')
    
    window.platformReport = () => {
      const report = generatePlatformReport(chatStore)
      console.log(report)
      return report
    }
    
    window.syncAdvice = () => {
      const advice = getCrossPlatformSyncAdvice()
      console.log('=== 跨平台同步建议 ===')
      advice.recommendations.forEach(rec => {
        console.log(`\n${rec.title}:`)
        rec.actions.forEach(action => console.log(`- ${action}`))
      })
      return advice
    }
    
    window.detectIssues = () => {
      const detection = detectPlatformDataInconsistency(chatStore)
      console.log('=== 问题检测结果 ===')
      console.log('统计:', detection.stats)
      console.log('问题:', detection.issues)
      console.log('需要同步:', detection.needsSync)
      console.log('需要清理:', detection.needsCleanup)
      return detection
    }
    
    // 自动运行检测
    const detection = detectPlatformDataInconsistency(chatStore)
    if (detection && detection.issues.length > 0) {
      console.warn('⚠️ 检测到数据问题，运行 window.platformReport() 查看详情')
    }
  }
} 